<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "{{%supplier}}".
 *
 * @property integer $id
 * @property string $name
 * @property string $remark
 * @property integer $shipping_type
 * @property string $code
 * @property integer $enable
 * @property integer $delivery_id
 * @property integer $deduct
 */
class Supplier extends \common\models\AR {

    const SHIPPING_TYPE_DELIVERY = 1;
    const SHIPPING_TYPE_SELF = 2;

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%supplier}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['name', 'shipping_type', 'code'], 'required'],
            [['shipping_type', 'enable', 'delivery_id', 'deduct'], 'integer'],
            [['name'], 'string', 'max' => 45],
            [['remark'], 'string', 'max' => 100],
            [['code'], 'string', 'max' => 4],
            [['code'], 'unique']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'name' => '名称',
            'remark' => '备注',
            'shipping_type' => '发货方式',
            'code' => '供应商代码',
            'enable' => '启用',
            'delivery_id' => '所属配送中心',
            'deduct' => '平台提成百分比',
        ];
    }

    public function beforeSave($insert) {
        if (parent::beforeSave($insert)) {
            if ($this->shipping_type == self::SHIPPING_TYPE_SELF) {
                $this->delivery_id = 0;
            }

            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取供应商保存图片的目录
     * @param string $type 图片类型 可选值：goodsAttr goodsGallery goodsDesc productImg
     * @param integer $supplierId 供应商ID
     * @return boolean|string 图片相对路径，如果无法得到目录，则返回FALSE，
     */
    public static function getImgPath($type, $supplierId = null) {
        $supplierId == NULL && $supplierId = Yii::$app->user->identity->supplier_id;
        $pathMap = [
            'goodsAttr' => "supplier/{$supplierId}/goods/attr",
            'goodsGallery' => "supplier/{$supplierId}/goods/gallery",
            'goodsDesc' => "supplier/{$supplierId}/goods/desc",
            'productImg' => "supplier/{$supplierId}/product/img",
        ];
        if (!array_key_exists($type, $pathMap)) {
            return FALSE;
        }
        $allPath = $pathMap[$type] . '/' . date('Ym');

        $pathArr = explode('/', $allPath);
        $path = Yii::getAlias('@img');
        foreach ($pathArr as $item) {
            $path.='/' . $item;
            !is_dir($path) && @mkdir($path);
        }

        return $allPath;
    }

}
